package com.lagou.kafka.demo.consumer;

import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.common.serialization.IntegerDeserializer;
import org.apache.kafka.common.serialization.StringDeserializer;

import java.util.*;
import java.util.function.Consumer;

/**
 * @param
 * @author oyz
 * @version 1.0
 * @description:  消费者
 * @date 2022/3/25 17:01
 */
public class MyConsumer1 {

    public static void main(String[] args) {
        Map<String,Object> configs = new HashMap<>();
        configs.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG,"192.168.106.130:9092");
        configs.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, IntegerDeserializer.class);
        configs.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
        // 配置消费组ID
        configs.put(ConsumerConfig.GROUP_ID_CONFIG,"consumer_demo1");
        // 如果找不到当前消费者的有效偏移量,则自动重置到最开始的位置
        // lastest表示直接重置到消息偏移量的最后一个位置
        configs.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG,"earliest");
        KafkaConsumer<Integer, String> consumer = new KafkaConsumer<>(configs);

        // 先订阅,再消费
        consumer.subscribe(Arrays.asList("topic_1"));
        // 批量的从主题分区中拉取消息
        ConsumerRecords<Integer, String> message = consumer.poll(3000);
         message.forEach(new Consumer<ConsumerRecord<Integer, String>>() {
            @Override
            public void accept(ConsumerRecord<Integer, String> record) {
                System.out.println(record.topic()+"\t"+record.partition()+"\t"+record.key()+"\t"
                        + record.value() +"\t"+record.offset());
            }
        });

        consumer.close();

    }
}
